//
//  StepTargetViewController.m
//  StormWatch
//
//  Created by Hero on 2024/9/5.
//

#import "StepTargetViewController.h"
#import <BRPickerView/BRStringPickerView.h>
@interface StepTargetViewController ()
@property (weak, nonatomic) IBOutlet UILabel *nameLab;
@property (weak, nonatomic) IBOutlet UILabel *subTextLab;
@property (weak, nonatomic) IBOutlet UILabel *valueLab;
/* <#note#> */
@property (nonatomic, strong) NSString * valueString;
@property (nonatomic, strong) NSArray * pickData;

@property (nonatomic, assign) DeviceCommandEnum type;
@property (nonatomic, strong) CBPeripheral * peripheral;

@end

@implementation StepTargetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * uuid = self.metaInfo[@"uuid"];
    NSArray * list = [FRQBluetoothManager shareManager].curPeripherals;
    for (CBPeripheral * per in list) {
        if ([per.identifier.UUIDString isEqualToString:uuid]) {
            self.peripheral = per;
        }
    }
    
    self.type = [self.metaInfo[@"action"] intValue];
    
    if (self.type == Command_StepGoal) {
        self.nameLab.text = self.navigationItem.title = SWString(@"Step goal");
        self.subTextLab.text = SWString(@"Set daily step goal");
        self.valueLab.text = @"--";
        self.jy_title = SWString(@"计步目标");
    }else if (self.type == Command_ScreenTime ) {
        self.nameLab.text = self.navigationItem.title = SWString(@"Screen time");
        self.subTextLab.text = SWString(@"Set watch screen time");
        self.valueLab.text = @"--";
        self.jy_title = SWString(@"亮屏时间");
    }
     
    self.valueLab.userInteractionEnabled = YES;
    [self.valueLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickValueLab  )]];
    
    [SWInitializer jy_initRedButtonWithTarget:self action:@selector(clickSureBtnAction) frame:CGRectMake(0, 0, kScreenWidth - 100, 50) title:SWString(@"Confirm") on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(50);
        kMakeBV(-100);
        kMakeWHV(kScreenWidth-100, 50);
    }];
    
  
    [self readData];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)readData {
    if (self.type == Command_StepGoal) {
        [[WatchCommandTool sharedInstance] readStepTargetData:^(BOOL success, unsigned long stepData) {
            self.valueString = [NSString stringWithFormat:@"%lu", stepData];
            self.valueLab.text = [NSString stringWithFormat:@"%lu%@",stepData,SWString(@"step")];
        } ToPeripheral:self.peripheral];
       
    }else if (self.type == Command_ScreenTime) {
        [[WatchCommandTool sharedInstance] readStormCommand:self.type ToPeripheral:self.peripheral reBack:^(NSString * _Nonnull backData) {
            if (backData) {
                NSString * valueStr = [backData substringWithRange:NSMakeRange(26, 2)];
                unsigned long value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                NSLog(@"当前数值：%lu",value);
                self.valueString = [NSString stringWithFormat:@"%lu", value];
                if (value == 0) {
                    self.valueLab.text = SWString(@"Steady on");
                }else {
                    self.valueLab.text = [NSString stringWithFormat:@"%lu%@",value,SWString(@"second")];
                }
            }
        }];
    }
   
}

- (void)clickValueLab {
    
   
    if (self.type == Command_StepGoal) {
        NSString * title = self.nameLab.text;
        NSString * subTitle = [NSString stringWithFormat:@"%@:%@",SWString(@"Current Goal"),self.valueLab.text];
        NSString * tfPlaceText = SWString(@"enter_new_goal (step)");
        __block UITextField *tf = nil;
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(subTitle)
        .LeeAddTextField(^(UITextField *textField) {
            // 这里可以进行自定义的设置
            textField.placeholder = tfPlaceText;
            if (@available(iOS 13.0, *)) {
                textField.textColor = [UIColor secondaryLabelColor];
            } else {
                textField.textColor = [UIColor darkGrayColor];
            }
            textField.keyboardType = UIKeyboardTypeNumberPad;
            tf = textField; //赋值
        })
        .LeeAction(SWString(@"Confirm"), ^{
            self.valueLab.text = [NSString stringWithFormat:@"%@%@",tf.text,SWString(@"step")];
            self.valueString = [NSString stringWithFormat:@"%@", tf.text];

        })
        .leeShouldActionClickClose(^(NSInteger index){
            // 是否可以关闭回调, 当即将关闭时会被调用 根据返回值决定是否执行关闭处理
            // 这里演示了与输入框非空校验结合的例子
            BOOL result = ![tf.text isEqualToString:@""];
            result = index == 0 ? result : YES;
            return result;
        })
        .LeeCancelAction(SWString(@"Cancel"), nil) // 点击事件的Block如果不需要可以传nil
        .LeeShow();
    }else if (self.type == Command_ScreenTime) {
       
        [BRStringPickerView showPickerWithTitle:nil dataSourceArr:self.pickData selectIndex:0 resultBlock:^(BRResultModel * _Nullable resultModel) {
            self.valueLab.text = resultModel.value;
            self.valueString = [NSString stringWithFormat:@"%ld",(long)resultModel.index];
        }];
        
    }
    
}

- (void) clickSureBtnAction {
    
    int value = self.valueString.intValue;
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    if (self.type == Command_StepGoal) {
        unsigned char byte1 = (value & 0xff000000)>>24;
        unsigned char byte2 = (value & 0xff0000)>>16;
        unsigned char byte3 = (value & 0xff00)>>8;
        unsigned char byte4 = (value & 0xff);
        
        arr[0] = @(byte1);
        arr[1] = @(byte2);
        arr[2] = @(byte3);
        arr[3] = @(byte4);

        [[WatchCommandTool sharedInstance] writeStormCommand:self.type ToPeripheral:self.peripheral Value:arr reBack:^(NSString * _Nonnull backData) {
            if (backData) {
                if ([backData hasSuffix:@"00"]) {
                    toast(SWString(@"Success"));
                    [[NSUserDefaults standardUserDefaults] setValue:@(value) forKey:@"Storm_steptarget"];
                }else {
                    toast(SWString(@""));
                }
    //            [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else {
        unsigned char byte1 = (value & 0xff);
        
        arr[0] = @(byte1);
        
        [[WatchCommandTool sharedInstance] writeStormCommand:self.type ToPeripheral:self.peripheral Value:arr reBack:^(NSString * _Nonnull backData) {
            if (backData) {
                if ([backData hasSuffix:@"00"]) {
                    toast(SWString(@"Success"));
                }else {
                    toast(SWString(@""));
                }
    //            [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
 
}

- (NSArray *)pickData {
    if (!_pickData) {
        NSMutableArray * arr = [[NSMutableArray alloc] initWithObjects:SWString(@"Steady on" ), nil];
        for (int i = 1; i < 60; i ++) {
            [arr addObject:[NSString stringWithFormat:@"%d %@",i ,SWString(@"second")]];
        }
        _pickData = arr;
    }
    return _pickData;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
